package api

import (
	"compress/gzip"
	"fmt"
	"gitee.com/xuyiping_admin/pkg/apierr"
	"io/ioutil"
	"kpt-dtm/http/middleware"
	"net/http"
	"strconv"

	"gitee.com/xuyiping_admin/pkg/xerr"
	"github.com/gin-gonic/gin"
)

func Health(c *gin.Context) {
	c.String(http.StatusOK, ":)")
}

func Handle404(c *gin.Context) {
	c.String(http.StatusNotFound, "404 NotFound")
}

func dumpPerfEventBody(c *gin.Context) ([]byte, error) {
	if c.ContentType() != "application/octet-stream" {
		return nil, fmt.Errorf("invalid Content-Type:  %s ", c.ContentType())
	}
	if c.GetHeader("Content-Encoding") != "gzip" {
		return nil, fmt.Errorf("invalid Content-Encoding:  %s ", c.GetHeader("Content-Encoding"))
	}
	if c.Request.Body == nil || int(c.Request.ContentLength) < 1 {
		return nil, fmt.Errorf("invalid body:  %v ", int(c.Request.ContentLength))
	}

	reader, err := gzip.NewReader(c.Request.Body)
	if err != nil {
		return nil, xerr.WithStack(err)
	}
	defer reader.Close()

	return ioutil.ReadAll(reader)
}

func Hello(c *gin.Context) {
	c.String(http.StatusOK, "hello world!")
}
func Auth(c *gin.Context) {
	idStr := c.Param("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	res, err := middleware.DtmOperation(c).OpsService.OldAuth(c, id)
	if err != nil {
		apierr.ClassifiedAbort(c, err)
		return
	}
	c.JSON(http.StatusOK, res)
}

func Test(c *gin.Context) {
	idStr := c.PostForm("id")
	id, _ := strconv.ParseInt(idStr, 10, 64)
	name := c.PostForm("name")
	err := middleware.DtmOperation(c).OpsService.OldTest(c, id, name)
	if err != nil {
		apierr.ClassifiedAbort(c, err)
		return
	}
	c.JSON(http.StatusOK, gin.H{"msg": "ok"})
}
